import { login, getInfo } from '@/api/login'
import storage from '@/utils/app-storage'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import _ from 'lodash';

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: storage.getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const UserName = userInfo.UserName.trim()
        const PassWord = userInfo.PassWord
        const Code = userInfo.Code
        const UUID = userInfo.UUID
        return new Promise((resolve, reject) => {
          login({ UserName, PassWord, Code, UUID }).then(resp => {
            storage.setToken(resp.data)
            this.token = resp.data
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            console.log('GetUserInfo data', res)
            const user = _.get(res, 'tables[0].table[0]', {});
            const roles = _.get(res, 'tables[1].table', []);
            const menus = _.get(res, 'tables[2].table', []);

            let avatar = user.Avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = roles.map(role => role.RoleKey);
              this.permissions = [...new Set(menus.filter(menu => !!menu.Perms).map(menu => menu.Perms))];
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.ID
            this.name = user.CompanyName
            this.avatar = avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          storage.delToken();
          resolve()
        })
      }
    }
  })

export default useUserStore
